<?php
namespace api\user\controller;

use api\common\controller\RestUserBaseController;
use think\Db;
use think\Validate;
use api\user\model\UserModel;
use fast\Random;
use think\request;

class ProfileController extends RestUserBaseController
{
    // 用户密码修改
    public function changePassword()
    {
        $validate = new Validate([
            'old_password'     => 'require',
            'password'         => 'require',
            'confirm_password' => 'require|confirm:password'
        ]);

        $validate->message([
            'old_password.require'     => '请输入您的旧密码!',
            'password.require'         => '请输入您的新密码!',
            'confirm_password.require' => '请输入确认密码!',
            'confirm_password.confirm' => '两次输入的密码不一致!'
        ]);

        $data = $this->request->param();
        if (!$validate->check($data)) {
            $this->error($validate->getError());
        }

        $userId       = $this->getUserId();
        $userPassword = Db::name("user")->where('id', $userId)->value('user_pass');

        if (!cmf_compare_password($data['old_password'], $userPassword)) {
            $this->error('旧密码不正确!');
        }

        Db::name("user")->where('id', $userId)->update(['user_pass' => cmf_password($data['password'])]);

        $this->success("密码修改成功!");

    }

    // 用户支付密码设置
    public function setPaypassword()
    {
        $validate = new Validate([
            'pay_password'         => 'require|number|length:6',
            'confirm_pay_password' => 'require|confirm:pay_password',
            'verification_code'    => 'require'
        ]);

        $validate->message([
            'pay_password.require'         => '请输入支付密码',
            'pay_password.number'          => '支付密码是数字',
            'pay_password.length'          => '支付密码为6位数字',
            'confirm_pay_password.require' => '请确认支付密码',
            'confirm_pay_password.confirm' => '两次输入的不一致',
            'verification_code.require'    => '请输入手机验证码'
        ]);

        $data = $this->request->param();
        if (!$validate->check($data)) {
            $this->error($validate->getError());
        }
        $userId = $this->getUserId();
        $mobile = Db::name("user")->where('id', $userId)->value('mobile');
        $errMsg = cmf_check_verification_code($mobile, $data['verification_code']);
        if (!empty($errMsg)) {
            $this->error($errMsg);
        }
        $user['pay_salt']     = Random::alnum();
        $user['pay_password'] = getEncryptPassword($data['pay_password'], $user['pay_salt']);
        Db::name("user")->where('id', $userId)->update($user);

        $this->success("支付密码设置成功");

    }

    // 用户绑定邮箱
    public function bindingEmail()
    {
        $validate = new Validate([
            'email' => 'require|email|unique:user,email',
            // 'verification_code' => 'require'
        ]);

        $validate->message([
            'email.require'             => '请输入您的邮箱',
            'email.email'               => '请输入正确的邮箱格式',
            'email.unique'              => '邮箱账号已存在',
            // 'verification_code.require' => '请输入数字验证码!'
        ]);

        $data = $this->request->param();
        if (!$validate->check($data)) {
            $this->error($validate->getError());
        }

        $userId    = $this->getUserId();
        $userEmail = Db::name("user")->where('id', $userId)->value('email');

        if (!empty($userEmail)) {
            $this->error("您已经绑定邮箱!");
        }

        // $errMsg = cmf_check_verification_code($data['email'], $data['verification_code']);
        // if (!empty($errMsg)) {
        //     $this->error($errMsg);
        // }

        Db::name("user")->where('id', $userId)->update(['email' => $data['email']]);

        $this->success("绑定成功!");
    }

    // 用户绑定手机号
    public function bindingMobile()
    {
        $validate = new Validate([
            'mobile'            => 'require|unique:user,mobile',
            'verification_code' => 'require'
        ]);

        $validate->message([
            'mobile.require'            => '请输入您的手机号!',
            'mobile.unique'             => '手机号已经存在！',
            'verification_code.require' => '请输入数字验证码!'
        ]);

        $data = $this->request->param();
        if (!$validate->check($data)) {
            $this->error($validate->getError());
        }

        if (!cmf_check_mobile($data['mobile'])) {
            $this->error("请输入正确的手机格式!");
        }


        $userId = $this->getUserId();
        $mobile = Db::name("user")->where('id', $userId)->value('mobile');

        if (!empty($mobile)) {
            $this->error("您已经绑定手机!");
        }

        $errMsg = cmf_check_verification_code($data['mobile'], $data['verification_code']);
        if (!empty($errMsg)) {
            $this->error($errMsg);
        }

        Db::name("user")->where('id', $userId)->update(['mobile' => $data['mobile']]);

        $this->success("绑定成功!");
    }

    /**
     * 用户基本信息获取及修改
     * @param 请求为GET 获取信息
     * @param [string] $[field] [要获取的一个或多个字段名] 可选
     * @return 带参数,返回某个或多个字段信息。不带参数，返回所有信息
     * @param 请求为POST 修改信息
     */
    public function userInfo($field = '')
    {
        //判断请求为GET，获取信息
        $userModel = new UserModel();
        $userId   = $this->getUserId();
        if ($this->request->isGet()) {
            $userData = $userModel->get($userId);
            //加速矿机
            // $minerModel = new \api\user\model\UserMinerModel();
            // $miner = $minerModel->where("user_id = {$userId} AND status = 1")->where('virtual',1)->sum('arithmetic_value');
            // $userData['miner'] = $miner ? $miner : 0;
            $this->success('请求成功',$userData);
        } 
        //判断请求为POST,修改信息
        if ($this->request->isPost()) {
            $param = $this->request->param();
            $updatetime =  Db::name("user")->where('id', $userId)->value('updatetime');
            $now = time();
            if(($updatetime+30*60*60*24)>$now){
                $this->error('距离上次修改不足30天');
            }
            if (!empty($data['nickname'])) {
                $this->error('修改失败');
            }
            $data['updatetime'] = time();
            $data['nickname'] = $param['nickname'];

            // 启动事务
            Db::startTrans();
            try{
                Db::name("user")->where('id', $userId)->update($data);
                // $user_verifytask = Db::name('user_task')
                // ->where(['task_id'=>1,'user_id'=>$userId])
                // ->find();
                // if(!$user_verifytask){
                //     $task_reward = Db::name('task')
                //     ->where(['id'=>1])
                //     ->value('task_reward');
                //     if($task_reward){
                //         Db::name('user')
                //         ->where(['id'=>$userId])
                //         ->update([
                //         'mission_wallet' => Db::raw('mission_wallet+'.$task_reward),
                //         ]);
                //         $user_balance_log['user_id']    = $userId;
                //         $user_balance_log['amount']     = $task_reward;
                //         $user_balance_log['before']     = $this->user['mission_wallet'];
                //         $user_balance_log['after']      = $this->user['mission_wallet']+$task_reward;
                //         $user_balance_log['remark']     = '完善个人资料任务';
                //         $user_balance_log['type']       = 1;
                //         $user_balance_log['log_type']   = 2;
                //         $user_balance_log['source']     = 2;
                //         $user_balance_log['task_id']    = 1;
                //         $user_balance_log['createtime'] = time();
                //         Db::name('user_balance_log')->insert($user_balance_log);
                //         Db::name('user_task')->insert(['task_id'=>1,'user_id'=>$userId,'createtime'=>date('Y-m-d')]);
                //     }
                // }
                // 提交事务
                Db::commit();  
                $this->success('修改成功');  
            }catch (\think\Exception\DbException $exception){
                // 回滚事务
                Db::rollback();
                $this->error('修改失败');
            }
        }
    }

    //绑定收款方式
    public function bindingPayment(){
        $userId   = $this->getUserId();
        $validate = new Validate([
            'type'  => 'require|number|between:1,3',
            'account_name'  => 'require',
            'account_number'  => 'require',
        ]);

        $validate->message([
            'type.require'           => '请选择账号类型',
            'account_name.require'   => '请输入姓名',
            'account_number.require' => '请输入账号'
        ]);

        $data = $this->request->param();
        if (!$validate->check($data)) {
            $this->error($validate->getError());
        }
        if($data['type'] ==3){
            if(!isset($data['account_bank_name'])){
                 $this->error('请输入开户行名称');
            }
            if(!isset($data['account_bank_address'])){
                 $this->error('请输入开户行名称');
            }
        }else{
            if(!isset($data['account_image'])){
                 $this->error('请上传收款码');
            }
        }
        switch ($data['type']) {
            case 1:
                $json['account_name'] = $data['account_name'];
                $json['account_number'] = $data['account_number'];
                $json['account_image'] = $data['account_image'];
                $account['wechatpay'] = json_encode($json);
                break;
            case 2:
                $json['account_name'] = $data['account_name'];
                $json['account_number'] = $data['account_number'];
                $json['account_image'] = $data['account_image'];
                $account['alipay'] = json_encode($json);
                break;
            case 3:
                $json['account_name'] = $data['account_name'];
                $json['account_number'] = $data['account_number'];
                $json['account_bank_name'] = $data['account_bank_name'];
                $json['account_bank_address'] = $data['account_bank_address'];
                $account['bankpay'] = json_encode($json);
                break;
            default:
                $this->error('绑定失败');
                break;
        }
        // 启动事务
        Db::startTrans();
        try{
            Db::name("user")->where('id', $userId)->update($account);
            // $user_verifytask = Db::name('user_task')
            // ->where(['task_id'=>4,'user_id'=>$userId])
            // ->find();
            // if(!$user_verifytask){
            //     $task_reward = Db::name('task')
            //     ->where(['id'=>4])
            //     ->value('task_reward');
            //     if($task_reward){
            //         Db::name('user')
            //         ->where(['id'=>$userId])
            //         ->update([
            //         'mission_wallet' => Db::raw('mission_wallet+'.$task_reward),
            //         ]);
            //         $user_balance_log['user_id']    = $userId;
            //         $user_balance_log['amount']     = $task_reward;
            //         $user_balance_log['before']     = $this->user['mission_wallet'];
            //         $user_balance_log['after']      = $this->user['mission_wallet']+$task_reward;
            //         $user_balance_log['remark']     = '添加收付款方式任务';
            //         $user_balance_log['type']       = 1;
            //         $user_balance_log['log_type']   = 2;
            //         $user_balance_log['source']     = 2;
            //         $user_balance_log['task_id']    = 4;
            //         $user_balance_log['createtime'] = time();
            //         Db::name('user_balance_log')->insert($user_balance_log);
            //         Db::name('user_task')->insert(['task_id'=>4,'user_id'=>$userId,'createtime'=>date('Y-m-d')]);
            //     }
            // }
            // 提交事务
            Db::commit();  
            $this->success('绑定成功');  
        }catch (\think\Exception\DbException $exception){
            // 回滚事务
            Db::rollback();
            $this->error('绑定失败');
        }

    }

    public function getBtcAddress(){
        $userId   = $this->getUserId();
        $userInfo = Db::name('user')->where('id',$userId)->find();
        if(!empty($userInfo['usdt_address'])){
            $this->success('已有地址');
        }
        $url = "http://18.182.36.161/api/Bitcoin/createAddress?username=".$userInfo['username']."&prefix=bitspace&token=ddbd2b932c763ba5b1b7ae3b362eac3e8d40121";
        $output = @geturl($url);
        if(isset($output['data']) && !empty($output['data'])){
            $res = Db::name('user')->where('id',$userId)->setField('usdt_address',$output['data']);
            if($res){
                $this->success('获取成功',$output['data']);
            }else{
                $this->error('服务器错误');
            }
        }else{
            $this->error('获取失败');
        }
    }

    /**
     * 提币
     */
    public function exchange(){
        $data['amount'] = $this->request->param('money');
        $data['address'] = $this->request->param('address');
        $data['memo'] = $this->request->param('remark');
        $validate = new Validate([
            'amount'  => 'require|number|gt:200',
            'address'  => 'require',
        ]);
        $validate->message([
            'amount.require'    => '请选择金额',
            'amount.gt'         => '请选择正确的金额',
            'address.require' => '请输入钱包地址'
        ]);
        if (!$validate->check($data)) {
            $this->error($validate->getError());
        }
        $data['user_id'] =  $this->getUserId();
        $data['status'] =2;
        $data['type'] =2;
        $data['create_time'] = time();
        $result = Db::name('block_chain_trade')->insert($data);
    }


    //绑定钱包
    public function bindingWallet(){
        $userId   = $this->getUserId();
        $validate = new Validate([
            'type'  => 'require',
            'address'  => 'require',
        ]);

        $validate->message([
            'type.require'    => '请选择钱包类型',
            'address.require' => '请输入钱包地址'
        ]);

        $data = $this->request->param();
        if (!$validate->check($data)) {
            $this->error($validate->getError());
        }
        
        switch ($data['type']) {
            case 'ipst':
                $account['ipst_address'] = $data['address'];
                $account['ipst_address_remark'] = isset($data['remark'])?$data['remark']:'';
                break;
            case 'usdt':
                $account['usdt_address'] = $data['address'];
                $account['usdt_address_remark'] = isset($data['remark'])?$data['remark']:'';
                break;
            case 'btc':
                $account['btc_address'] = $data['address'];
                $account['btc_address_remark'] = isset($data['remark'])?$data['remark']:'';
                break;
            case 'eth':
                $account['eth_address'] = $data['address'];
                $account['eth_address_remark'] = isset($data['remark'])?$data['remark']:'';
                break;
            default:
                $this->error('绑定失败');
                break;
        }
        // 启动事务
        Db::startTrans();
        try{
            $upData = Db::name("user")->where('id', $userId)->update($account);
            $user_verifytask = Db::name('user_task')
            ->where(['task_id'=>5,'user_id'=>$userId])
            ->find();
            if(!$user_verifytask){
                $task_reward = Db::name('task')
                ->where(['id'=>5])
                ->value('task_reward');
                if($task_reward){
                    Db::name('user')
                    ->where(['id'=>$userId])
                    ->update([
                    'mission_wallet' => Db::raw('mission_wallet+'.$task_reward),
                    ]);
                    $user_balance_log['user_id']    = $userId;
                    $user_balance_log['amount']     = $task_reward;
                    $user_balance_log['before']     = $this->user['mission_wallet'];
                    $user_balance_log['after']      = $this->user['mission_wallet']+$task_reward;
                    $user_balance_log['remark']     = '添加/验证提币地址';
                    $user_balance_log['type']       = 1;
                    $user_balance_log['log_type']   = 2;
                    $user_balance_log['source']     = 2;
                    $user_balance_log['task_id']    = 5;
                    $user_balance_log['createtime'] = time();
                    Db::name('user_balance_log')->insert($user_balance_log);
                    Db::name('user_task')->insert(['task_id'=>5,'user_id'=>$userId,'createtime'=>date('Y-m-d')]);
                }
            }
            // 提交事务
            Db::commit();  
            $this->success('绑定成功');
        }catch (\think\Exception\DbException $exception){
            // 回滚事务
            Db::rollback();
            $this->error('绑定失败');
        }
       
    }

    public function myteam(){
        $userId = $this->getUserId();
        $UserModel =new UserModel();
        $param = $this->request->param();
        if (!empty($param['page'])) {
            $map['page'] = $param['page'];
        }
        //直推用户
        if($param['type']){
            //$where['status'] =1;
            $where['invite_user_id'] = $userId;
            $user_ids = Db::name("invite")->where($where)->column('user_id');
            $map['where'] = [
                'id'=>['in',$user_ids]
            ];
            $data = $UserModel->getDatas($map);
        }else{
            $where[] = ['exp',Db::raw("FIND_IN_SET($userId,path)")];
            $where['user_id'] = ['neq',$userId];
            $team_ids = Db::name("invite")->where($where)->column('user_id');
            // print_r($team_ids);
            // die;
            $map['where'] = [
                'id'=>['in',$team_ids]
            ];
            $data = $UserModel->getDatas($map);
        }

        $this->success('请求成功', ['list' => $data]);
    }

    //创建FIL3提币订单
    public function creat_order(){
        $data['fil'] = $this->request->param('coin_value');
        $data['address'] = $this->request->param('address');
        $data['user_id'] = $this->getUserId();
        $data['order_no']= cmf_get_order_sn();
        $data['order_source'] = 2;
        $data['order_type'] = 2;
        $data['order_title'] ='FIL3提币';
        $data['transfer_fee'] = 5;
        $data['createtime'] = time();
        $user_info = Db::name('user')->where('id',$this->getUserId())->find();
        if($user_info['fil_wallet'] < $data['fil']){
            $this->error('FIL3余额不足');
        }
        $res = Db::name('user_order')->insert($data);
        if($res){
            $this->success('操作成功');
        }else{
            $this->error('操作失败');
        }
    }


}
